<template>
	<div class="cart">
		<!-- 导航栏 -->
		<van-nav-bar title="购物车"  left-arrow @click-left="onClickLeft" fixed>
		  <template #right>
		    <van-icon name="ellipsis" size="18" />
		  </template>
		</van-nav-bar>
		
		<div class="listcon">
			<van-swipe-cell v-for="item in list">
			  <div class="item" >
			  	<van-checkbox v-model="item.selected"></van-checkbox>
			  	<img :src="item.goodsCoverImg" alt="">
			      <div class="itemright">
			  	   <h3>{{item.goodsName}}</h3>
			  	   <div class="step">
			  		   <p>￥{{item.sellingPrice}}</p>
			  		   <van-stepper v-model="item.goodsCount" />
			  	   </div>
			  	</div>
			  </div>
			  
			  <template #right>
			    <van-button 
				square text="删除" 
				type="danger" 
				class="delete-button" 
				@click="deletecart(item.cartItemId)"
				/>
			  </template>
			</van-swipe-cell>
		</div>
	
	    <van-submit-bar :price="allprice" button-text="结算" @submit="onSubmit">
	      <van-checkbox v-model="checkedAll">全选</van-checkbox>
	    </van-submit-bar>
	</div>
</template>

<script>
	export default{
		name:"Cart",
		data(){
			return{
			}
		},
		created(){
			if(this.list==null){//如果list数据是null，发送请求
				this.$store.dispatch("asyncgetCartList")
			}
		},
		methods:{
			onClickLeft(){//返回上级目录
				this.$router.back();
			},
			onSubmit(){
				
			},
			deletecart(aid){
				this.$http.deleteCart(aid)
				.then(res=>{
					console.log(res);
					if(+res.resultCode===200){
						this.$store.dispatch("asyncgetCartList");
					}
				}).catch(err=>{
					console.log(err);
				})
			}
		},
		computed:{
			list(){//获取list数据
				return this.$store.state.list||[];
			},
			checkedAll:{
				get(){//获取全选的值
				    //每一项的结果为真，最终才为真
					return this.list.every(item=>{
						return item.selected==true;
					})
				},
				set(val){//设置选项的值
					this.list.map(item=>{//每一项的选择状态，由全选决定
						item.selected=val;
						return item;
					})
				}
			},
			allprice(){
				return this.list.reduce((result,item)=>{
					//选中元素的单价乘以数量，而且还要乘以100倍  3050---》30.50
					return result+(item.selected?item.sellingPrice*item.goodsCount*100:0)
				},0)
			}
		}
	}
</script>

<style scoped lang="less">
	.listcon{
		.item{
			width:90%;
			display:flex;
			margin:5%;
			img{
				width:30%;
			}
			h3{
				font-size:14px;
			}
			.step{
				display: flex;
		        p{
				  font-size:14px; 
				  color:red;
				  line-height:60px;
				  margin-right:60px;
				}
			}
		}
		.van-button--danger{
			height:100px;
			width:60px;
			line-height:100px;
		}
		margin-bottom:120px;
		margin-top:60px;
	}
	.van-submit-bar{
		bottom:50px;
	}
</style>
